﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;


using ECCIT;
using ECCIT.Data;
using ECCIT.Business.Model;
using ECCIT.Business.DAL;

using OgilvyOne.UKNow.Globalization;
using OgilvyOne.UKNow.Utility;
using OgilvyOne.UKNow.Model;
using OgilvyOne.UKNow.IDAL;

namespace OgilvyOne.UKNow.DAL
{
    public class MapKeyWordsDAL : UKNowBaseDAL
    {
        private const string TBL_NAME = "UKNOW_IMPRESS_KEYWORD";
        private const string COL_LANG_ID = "COL_LANG_ID";
        private const string COL_KEYWORD_ID = "COL_KEYWORD_ID";
        private const string COL_KEYWORD_NAME = "COL_KEYWORD_NAME";
        private const string COL_KEYWORD_TYPE = "COL_KEYWORD_TYPE";
        private const string COL_KEYWORD_COUNT = "COL_KEYWORD_COUNT";
        private const string COL_KEYWORD_STATE = "COL_KEYWORD_STATE";
        private const string COL_KEYWORD_INSERT_TIME = "COL_KEYWORD_INSERT_TIME";
        private const string COL_KEYWORD_UPDATE_TIME = "COL_KEYWORD_UPDATE_TIME";

        public override string TableName { get { return TBL_NAME; } }

        public override Type ModelType { get { return typeof(MapKeyWordsModel); } }

        [PrimaryKey]
        public IField LanguageID { get { return FieldFactory.Create(ModelType, "LanguageID", ColumnFactory.CreateColumn(COL_LANG_ID, DataType.Int)); } }

        [PrimaryKey]
        public IField ID { get { return FieldFactory.Create(ModelType, "ID", ColumnFactory.CreateColumn(COL_KEYWORD_ID, DataType.Int)); } }

        public IField Name { get { return FieldFactory.Create(ModelType, "Name", ColumnFactory.CreateColumn(COL_KEYWORD_NAME, DataType.String, 200)); } }
        public IField Type { get { return FieldFactory.Create(ModelType, "Type", ColumnFactory.CreateColumn(COL_KEYWORD_TYPE, DataType.Int)); } }
        public IField Count { get { return FieldFactory.Create(ModelType, "Count", ColumnFactory.CreateColumn(COL_KEYWORD_COUNT, DataType.Int)); } }
        public IField State { get { return FieldFactory.Create(ModelType, "State", ColumnFactory.CreateColumn(COL_KEYWORD_STATE, DataType.Int)); } }
        public IField InsertedTime { get { return FieldFactory.Create(ModelType, "InsertedTime", ColumnFactory.CreateColumn(COL_KEYWORD_INSERT_TIME, DataType.DateTime)); } }
        public IField UpdatedTime { get { return FieldFactory.Create(ModelType, "UpdatedTime", ColumnFactory.CreateColumn(COL_KEYWORD_UPDATE_TIME, DataType.DateTime)); } }

        public override IField[] InsertFields { get { return new IField[] { LanguageID, ID, Name, Type, Count, State, InsertedTime, UpdatedTime }; } }
        public override IField[] SelectFields { get { return InsertFields; } }
        public override IField[] UpdateFields { get { return new IField[] { LanguageID, Name, Type, Count, State, InsertedTime, UpdatedTime }; } }

        public MapKeyWordsDAL() { }

        public MapKeyWordsDAL(LanguageType languageType) { this.Language = LanguageFactory.Create(languageType); }


        #region IDALEvents Members

        public MapKeyWordsModel GetMapKeyWordsModelByID(int? id)
        {
            MapKeyWordsModel model = (MapKeyWordsModel)GetModelByPrimaryKey(this.GetType(), new KeyValuePair<IField, object>[] { new KeyValuePair<IField, object>(LanguageID, (int)this.Language.LanguageType), new KeyValuePair<IField, object>(this.ID, id) });
            return model;
        }


        public IList<MapKeyWordsModel> GetAllMapKeyWordsModels()
        {
            string whereClause = string.Format("where {0}={1}", COL_LANG_ID, (int)this.Language.LanguageType);
            IList<MapKeyWordsModel> models = GetModels(whereClause, PagingParameterFactory.CreateNonPagingParameter(SortingParameterFactory.CreateInstance(UpdatedTime.PropertyName, SortOrder.Desc))).List.Cast<MapKeyWordsModel>().ToList();

            return models;
        }

        public IList<MapKeyWordsModel> GetAllMapKeyWordsModelsByName(string Keyname)
        {
            string whereClause = string.Format("where {0}={1} and {2}='{3}'", COL_LANG_ID, (int)this.Language.LanguageType, COL_KEYWORD_NAME,Keyname);
            IList<MapKeyWordsModel> models = GetModels(whereClause, PagingParameterFactory.CreateNonPagingParameter(SortingParameterFactory.CreateInstance(UpdatedTime.PropertyName, SortOrder.Desc))).List.Cast<MapKeyWordsModel>().ToList();


            return models;
        }
        public IList<MapKeyWordsModel> GetAllMapKeyWordsModelsReleaseNsy()
        {
            string whereClause = string.Format("where {0}={1} and {2}={3} and {4}={5}", COL_LANG_ID, (int)this.Language.LanguageType, COL_KEYWORD_TYPE, 0,COL_KEYWORD_STATE,1);
            IList<MapKeyWordsModel> models = GetModels(whereClause, PagingParameterFactory.CreateNonPagingParameter(SortingParameterFactory.CreateInstance(UpdatedTime.PropertyName, SortOrder.Desc))).List.Cast<MapKeyWordsModel>().ToList();


            return models;
        }


        public IList<MapKeyWordsModel> GetPublishedMapKeyWordsModels()
        {
            WhereClauseBuilder builder = WhereClauseBuilder.CreateInstance(SearchConditionJoinOperator.AND);
            builder.Conditions.Add(CommonSearchCondition.CreateInstance(COL_KEYWORD_STATE, 1, SearchConditionOperator.Equals));
            builder.Conditions.Add(CommonSearchCondition.CreateInstance(COL_LANG_ID, (int)this.Language.LanguageType, SearchConditionOperator.Equals));

            string whereClause = builder.ToSqlCommand();
            IList<MapKeyWordsModel> models = GetModels(whereClause, PagingParameterFactory.CreateNonPagingParameter(SortingParameterFactory.CreateInstance(UpdatedTime.PropertyName, SortOrder.Desc))).List.Cast<MapKeyWordsModel>().ToList();

            return models;
        }

        public ResultInfo Save(MapKeyWordsModel modelInfo)
        {
            if (modelInfo == null) throw new ArgumentNullException("modelInfo");

            ResultInfo result = new ResultInfo(false);

            try
            {
                int rowsAffected = 0;
                if (modelInfo.ID == null)   // insert
                {
                    modelInfo.ID = SqlUtil.GetMaxRecordID(TableName, COL_KEYWORD_ID, COL_LANG_ID, (int)this.Language.LanguageType);
                    //modelInfo.State = 0;    // 强制将活动状态置为未发布
                    modelInfo.InsertedTime = DateTime.Now;
                    modelInfo.UpdatedTime = DateTime.Now;
                    rowsAffected = Insert(modelInfo, null);
                }
                else // update
                {
                    modelInfo.UpdatedTime = DateTime.Now;
                    rowsAffected = UpdateByPrimaryKey(modelInfo, null);
                }

                if (rowsAffected > 0)
                {
                    result.Message = "数据保存成功！";
                    result.Result = true;
                    result.ReturnObject = modelInfo;
                }
            }
            catch (Exception ex)
            {
                result.Exception = ex;
                result.Message = string.Format("保存数据时发生异常。异常信息：{0}", ex.Message);
            }

            return result;
        }

        public ResultInfo Delete(IList<int?> idList)
        {
            ResultInfo result = new ResultInfo(false);
            using (IDbConnection conn = DBHelper.GetDbConnection())
            {
                conn.Open();
                IDbTransaction trans = conn.BeginTransaction();
                try
                {
                    foreach (int? id in idList)
                        DeleteModelByPrimaryKey(trans, this.GetType(), new KeyValuePair<IField, object>[] { new KeyValuePair<IField, object>(LanguageID, (int)this.Language.LanguageType), new KeyValuePair<IField, object>(this.ID, id) });

                    trans.Commit();
                    result.Result = true;
                    result.Message = "数据删除成功！";
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    result.Message = string.Format("删除数据时发生异常。异常信息：{0}", ex.Message);
                }
                finally
                {
                    trans.Dispose();
                }
            }

            return result;
        }

        public ResultInfo Publish(IList<int?> idList)
        {
            ResultInfo result = new ResultInfo(false);

            IField[] updatedFields = new IField[] { this.State };
            IDataParameter[] parms = DBHelper.GetDataParameters(updatedFields);
            parms[0].Value = 1;

            string ids = "";
            foreach (int? id in idList)
                ids += (ids == string.Empty) ? id.ToString() : "," + id.ToString();

            WhereClauseBuilder builder = WhereClauseBuilder.CreateInstance(SearchConditionJoinOperator.AND);
            builder.Conditions.Add(InSearchCondition.CreateInstance(COL_KEYWORD_ID, DataType.Int, ids));
            builder.Conditions.Add(CommonSearchCondition.CreateInstance(COL_LANG_ID, (int)this.Language.LanguageType, SearchConditionOperator.Equals));

            string whereClause = builder.ToSqlCommand();
            string cmdText = DBHelper.GetUpdateCommandText(this.TableName, updatedFields, whereClause);

            try
            {
                DBHelper.ExecuteNonQuery(cmdText, parms);
                result.Result = true;
                result.Message = "发布成功！";
            }
            catch (Exception ex)
            {
                result.Message = string.Format("发布时发生异常。异常信息：{0}", ex.Message);
            }

            return result;
        }

        public ResultInfo UnPublish(IList<int?> idList)
        {
            ResultInfo result = new ResultInfo(false);

            IField[] updatedFields = new IField[] { this.State };
            IDataParameter[] parms = DBHelper.GetDataParameters(updatedFields);
            parms[0].Value = 0;

            string ids = "";
            foreach (int? id in idList)
                ids += (ids == string.Empty) ? id.ToString() : "," + id.ToString();

            WhereClauseBuilder builder = WhereClauseBuilder.CreateInstance(SearchConditionJoinOperator.AND);
            builder.Conditions.Add(InSearchCondition.CreateInstance(COL_KEYWORD_ID, DataType.Int, ids));
            builder.Conditions.Add(CommonSearchCondition.CreateInstance(COL_LANG_ID, (int)this.Language.LanguageType, SearchConditionOperator.Equals));

            string whereClause = builder.ToSqlCommand();
            string cmdText = DBHelper.GetUpdateCommandText(this.TableName, updatedFields, whereClause);

            try
            {
                DBHelper.ExecuteNonQuery(cmdText, parms);
                result.Result = true;
                result.Message = "取消发布成功！";
            }
            catch (Exception ex)
            {
                result.Message = string.Format("取消发布时发生异常。异常信息：{0}", ex.Message);
            }

            return result;
        }

        public ResultInfo SetMap(IList<int?> idList)
        {
            ResultInfo result = new ResultInfo(false);

            IField[] updatedFields = new IField[] { this.Count };
            IDataParameter[] parms = DBHelper.GetDataParameters(updatedFields);
            parms[0].Value = int.Parse(parms[0].Value.ToString())+ 1;

            string ids = "";
            foreach (int? id in idList)
                ids += (ids == string.Empty) ? id.ToString() : "," + id.ToString();

            WhereClauseBuilder builder = WhereClauseBuilder.CreateInstance(SearchConditionJoinOperator.AND);
            builder.Conditions.Add(InSearchCondition.CreateInstance(COL_KEYWORD_ID, DataType.Int, ids));
            builder.Conditions.Add(CommonSearchCondition.CreateInstance(COL_LANG_ID, (int)this.Language.LanguageType, SearchConditionOperator.Equals));

            string whereClause = builder.ToSqlCommand();
            string cmdText = DBHelper.GetUpdateCommandText(this.TableName, updatedFields, whereClause);

            try
            {
                DBHelper.ExecuteNonQuery(cmdText, parms);
                result.Result = true;
                result.Message = "投票成功！";
            }
            catch (Exception ex)
            {
                result.Message = string.Format("投票时发生异常。异常信息：{0}", ex.Message);
            }

            return result;
        }

        #endregion

    }

}
